#ifndef COMMON_H
#define COMMON_H

#include <QFile>
#include <QString>
#include <QStringList>

static inline int ip2num(QString ip)
{
    bool ok;
    int lp[4];
    QStringList iplist=ip.split('.');
    for (int i=0;i<iplist.length();i++)
        lp[i]=iplist[i].toInt(&ok,10);
    return lp[0] << 24 | lp[1] << 16 | lp[2] << 8 | lp[3];
}

static inline QString num2ip(int num)//:# int num to ip
{
    int ip[4];
    ip[3] = (num & 0xff);
    ip[2] = (num & 0xff00) >> 8;
    ip[1] = (num & 0xff0000) >> 16;
    ip[0] = (num & 0xff000000) >> 24;
    QString rip = QString("%1").arg(ip[0])+QString(".")+QString("%1").arg(ip[1])+QString(".")+QString("%1").arg(ip[2])+QString(".")+QString("%1").arg(ip[3]);
    return rip;
}

//检查ipv4地址是否合法
static inline bool checkip(QString ip)
{
    QRegExp rx2("\\d+\\.\\d+\\.\\d+\\.\\d+");
    if( !rx2.exactMatch(ip) )
    {
        return false;
    }
    //qDebug()<<"check true";
    return true;
}

// QString转char*
static inline char* qstring2charPointer(QString tmp)
{
    QByteArray text = tmp.toLocal8Bit();
    char * pCh = new char[text.size()+1];
    strcpy(pCh, text.data());
    return pCh;
}

static QString showservice(QString portnum)
{
    //qDebug() << "进入";
    QString result="";
    QString a="";
    QString b="";
    int i=0;
    //QFile file("C://network scanner//network-scanner//nmap-services.txt");
    QFile file(":/res/nmap-services.txt");
    if (file.open(QIODevice::ReadOnly | QIODevice::Text))
    {
        //qDebug() << "文件打开成功";
        while (!file.atEnd())
        {
            //qDebug() << "开始";
            QByteArray line = file.readLine();
            QString str(line);
            //qDebug() << str;
            for(i=0;str[i]>='a'&&str[i]<='z';i++)
            {
                a=a+str[i];
            }
            while(!((str[i]>='0')&&(str[i]<='9')))
            {
                i++;
            }
            for(;str[i]>='0'&&str[i]<='9';i++)
            {
                b=b+str[i];
            }
            if(portnum==b)
            {
                result=a;
                a="";
                b="";
                break;
            }
            a="";
            b="";

        }
        file.close();

    }
    //qDebug() << result;
    return result;
}

#endif // COMMON_H
